local contamination_difficulty = {}
local modpath = minetest.get_modpath("contamination")
contamination_difficulty["easy"] = 32
contamination_difficulty["medium"] = 16
contamination_difficulty["hard"] = 8
contamination_difficulty["calamity"] = 4

dofile(modpath.."/items.lua")
dofile(modpath.."/nodes.lua")
dofile(modpath.."/craft.lua")

local difficulty = minetest.settings:get("contamination.difficulty") or 0.0

if not contamination_difficulty[difficulty] then difficulty = "medium" end

local contaminated_versions = {}
local contaminate_neighbors = {}

contamination_register_contaminatable = function(name, contaminated_name)
	contaminated_versions[name] = contaminated_name
	contaminate_neighbors[#contaminate_neighbors + 1] = name
end

dofile(modpath.."/spread_nodes.lua")

local m
local contaminateNode = function(p)
	if minetest.is_protected(p, "") then return end
	local n=minetest.get_node_or_nil(p)
	if not n then return end
	local n_reg=minetest.registered_nodes[n.name]
	if not n_reg then return end
	if n_reg.groups["contaminated"] then return end
	m = minetestd.utils.check_item_match(n.name, contaminate_neighbors)
	if m then
		minetest.set_node(p, {name=contaminated_versions[m], param2=n.param2})
	end
	
end

minetest.after(0, function()
	for name,_ in pairs(minetest.registered_nodes) do
		if minetestd.utils.check_item_match(name, contaminate_neighbors) then
			minetest.registered_nodes[name].groups.can_contaminate = 1
		end
	end
end)

minetest.register_abm({
	nodenames={"group:contaminated"},
	neighbors={"group:can_contaminate"},
	interval=1,
	chance=contamination_difficulty[difficulty],
	catch_up=false,
	action=function(p)
		p.x = p.x + 2.125*(math.random() - 0.5)
		p.y = p.y + 2.125*(math.random() - 0.5)
		p.z = p.z + 2.125*(math.random() - 0.5)
		contaminateNode(p)
	end,
})